#include <random.h>
#include <user.h>
#include <timer.h>
#include <defs.h>

void RandomServer() {
  random_req msg;
  int reply = 1;
  int sender_tid;

  // notify parent
  int parent_tid;
  Receive(&parent_tid, NULL, 0);
  Reply(parent_tid, NULL, 0);  
  
  RegisterAs("random-server");
  
  for ( ; ; ) {
    Receive(&sender_tid, (char*)&msg, sizeof(random_req));
    switch (msg.type) {
    case RAND_MSG:
      reply = reply * 1103515245 + 12345;
      Reply(sender_tid, (char*)&reply, sizeof(int));
      break;
    case SRAND_MSG:
      reply = msg.seed;
      Reply(sender_tid, NULL, 0);
      break;
    default:
      Panic("RandomServer", "invalid message type");
    }
  }
  Panic("RandomServer", "Chuck Norris!");
}

int Rand() {
  random_req msg;
  int result;
  int random_tid = WhoIs("random-server");
  msg.type = RAND_MSG;
  Send(random_tid, (char*)&msg, sizeof(random_req), (char*)&result, sizeof(int));
  return result;
}

int SRand(int seed) {
  random_req msg;
  int result;
  int random_tid = WhoIs("random-server");
  msg.type = SRAND_MSG;
  msg.seed = seed;
  Send(random_tid, (char*)&msg, sizeof(random_req), NULL, 0);
  return Rand();
}
